#!/usr/bin/env python
import cgi
import datetime
import urllib
import webapp2

from google.appengine.ext import db
from google.appengine.api import users

class TemperatureReading(db.Model):
  """Models an individual temperature data point."""
  sensor_id = db.StringProperty()
  date = db.DateTimeProperty(auto_now_add=True)
  humidity = db.FloatProperty()
  celcius = db.FloatProperty()

def device_key(sensor_id=None):
    """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
    return db.Key.from_path('sensor_id', sensor_id or 'default_sensor_id')

class MainHandler(webapp2.RequestHandler):
    def get(self):
      self.response.out.write('<html><body>')
      sensor_id = self.request.get('sensor_id')
      key = device_key(sensor_id)
      readings = db.GqlQuery("SELECT * "
                              "FROM TemperatureReading "
                              "WHERE ANCESTOR IS :1 "
                              "ORDER BY date DESC LIMIT 100",
                              key)

      self.response.out.write("""
      <table>
      <tr><th>Time</th><th>Humidity</th><th>Celcius</th><th>Fahr</th></tr>
      """)
      for reading in readings:
        fahr = reading.celcius * (9.0 / 5.0) + 32;
        self.response.out.write('<tr><td>%s</td><td>%0.2f</td><td>%0.2f</td><td>%0.2f</td></tr>' % (reading.date, reading.humidity, reading.celcius, fahr))
        # self.response.out.write('<tr><td>%s, %s, %0.2f, %0.2f, %0.2f<br/>' % (sensor_id, reading.date, reading.humidity, reading.celcius, fahr))

      self.response.out.write('</table>')
      
      self.response.out.write("""
        <form action="/post?%s" method="post">
          <div><input type="text" value="%s" name="sensor_id" /></div>
          <div><input type="text" name="humidity" /></div>
          <div><input type="text" name="celcius" /></div>
          <div><input type="submit" value="Post"></div>
        </form>
        </body>
        </html>""" % (urllib.urlencode({'sensor_id': sensor_id}), cgi.escape(sensor_id)))

class TemperatureLogger(webapp2.RequestHandler):
  def post(self):
    sensor_id = self.request.get('sensor_id')
    reading = TemperatureReading(parent=device_key(sensor_id))
    reading.sensor_id = sensor_id
    reading.humidity = float(self.request.get('humidity'))
    reading.celcius = float(self.request.get('celcius'))
    reading.put()
    self.redirect('/?' + urllib.urlencode({'sensor_id': sensor_id}))

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/post', TemperatureLogger)],
                              debug=True)
